<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="friendName"
            placeholder="请输入好友名称"
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="friendList"
            :props="defaultProps"
            ref="tree"
            node-key="id"
            default-expand-all
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">


        <el-row  :gutter="10" class="mb8">
          <div style="text-align: center">{{charUserName}}</div>
        </el-row>



        <div style="background: #F4F5F7;padding: 20px">

          <div  ref="mianscroll" class="chat-msg" >
            <div :class="item.sendUserId == userId?'bubble1':'bubble'" v-for="item in chatMsgList">

              <img :src="item.sendAvatar" style="width:45px;border-radius:50%;color: #fff;font-size: 19px;line-height: 20px;margin-right: 15px;margin-left: 15px">
              <div :class="item.sendUserId == userId?'msg-content':'msg-content1'">
                <div>
                  {{ item.contents}}
                </div>
                <div style="margin:2px;font-size: 10px;color: #bfbfbf">
                  {{item.sendTime}}
                </div>
              </div>
            </div>

          </div>
          <div class="write" style=" width:1100px;margin-bottom: 40px;margin-top: 20px">

            <div style="width: 700px;margin-right:30px">
              <el-input
                v-model="form.contents"
                placeholder="请输入消息内容"
                clearable
                @keyup.enter.native="sendWebsocketMsg"
                maxlength="50"
                show-word-limit
              />
            </div>
            <el-button type="primary" @click="sendWebsocketMsg"  >发送</el-button>

          </div>
        </div>



      </el-col>
    </el-row>

    <!-- 添加或修改聊天记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发送用户的id" prop="sendUserId">
          <el-input v-model="form.sendUserId" placeholder="请输入发送用户的id" />
        </el-form-item>
        <el-form-item label="接收用户的id" prop="receiveUserId">
          <el-input v-model="form.receiveUserId" placeholder="请输入接收用户的id" />
        </el-form-item>
        <el-form-item label="消息内容" prop="contents">
          <el-input v-model="form.contents" placeholder="请输入消息内容" />
        </el-form-item>
        <el-form-item label="发送时间" prop="sendTime">
          <el-date-picker clearable
            v-model="form.sendTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发送时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listChatMsg, getChatMsg, delChatMsg, addChatMsg, updateChatMsg } from "@/api/petSys/chatMsg";
import { listAttention, getAttention, delAttention, addAttention, updateAttention ,selectNotAttentionUserList,updateFriendApply} from "@/api/petSys/attention";
export default {
  name: "ChatMsg",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 聊天记录表格数据
      chatMsgList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sendUserId: null,
        receiveUserId: null,
        contents: null,
        sendTime: null,
      },
      defaultProps: {
        children: "children",
        label: "remark"
      },
        friendList:[],
        friendName:'',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      charUserId:0,
      websocket:null,
      userId:0,
      charUserName:"",
      sendAvatar:""

    };
  },
  watch: {
    // 根据名称筛选树
    friendName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {

    this.sendAvatar = this.$store.state.user.avatar;
  },
  mounted() {
    this.userId = this.$store.state.user.id;


    this.getFriendList();

    this.webSocketConfig();
    this.bottomScrollClick();

  },
  methods: {
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.friendNickName.indexOf(value) !== -1;
    },
    /** 查询聊天记录列表 */
    getList() {
      console.log("queryParams",this.queryParams)
      this.loading = true;
      listChatMsg(this.queryParams).then(response => {
        this.chatMsgList = response.rows;
        console.log("chatMsgList",this.chatMsgList)
        this.total = response.total;
        this.loading = false;
        this.bottomScrollClick()
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sendUserId: null,
        receiveUserId: null,
        contents: null,
        sendTime: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加聊天记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getChatMsg(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改聊天记录";
      });
    },
    /** 提交按钮 */
    submitForm() {


          if (this.form.id != null) {
            updateChatMsg(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChatMsg(this.form).then(response => {
              // this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.form.contents = "";
              // this.getList();
            });
          }


    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除聊天记录编号为"' + ids + '"的数据项？').then(function() {
        return delChatMsg(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /**
     * 获取好友列表
     */
    getFriendList(){

      let params = {
        attentionUserId:this.userId
      }

      listAttention(params).then(response => {
        console.log(response)


        // this.friendList = response.rows;
        response.rows.forEach((item)=>{

          if(item.remark==null||item==""){

            item.remark = item.friendNickName;
          }

          this.friendList.push(item);
        })
        console.log("friendList",this.friendList)
        if(this.friendList.length>0){
          this.form.receiveUserId = this.friendList[0].beAttentionUserId;
          this.charUserName= this.friendList[0].remark;
        }

        this.queryParams.receiveUserId = this.form.receiveUserId
        this.queryParams.sendUserId = this.userId

        this.getList();

      })
    },
    handleNodeClick(data){

      this.form.nickName = data.friendNickName;
      this.form.receiveUserId = data.beAttentionUserId;
      this.queryParams.receiveUserId = this.form.receiveUserId
      this.queryParams.sendUserId = this.userId
      this.charUserName = data.remark
      this.getList();

    },
    sendWebsocketMsg(){


      // this.form.receiveUserId = this.charUserId;

      // console.log(this.charUserId);
      if(this.form.contents!=null&&this.form.contents.trim().length!=0 &&this.form.receiveUserId !=null){
        this.form.sendUserId = this.userId;
        const date = new Date();

// 使用模板字面量和Date对象的方法创建所需格式的字符串
        const formattedDate = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;

        console.log( "这里是接收者id",this.form.receiveUserId)
        this.form.sendTime =formattedDate;
        //用于发送websocket
        var msg = {};

        msg.receiveUserId = this.form.receiveUserId
        msg.sendUserId = this.userId;
        msg.contents = this.form.contents
        msg.sendTime = formattedDate;
        msg.sendUserName = this.$store.state.user.nickName;
        msg.sendAvatar = this.sendAvatar;
        console.log("准备发送msg",msg)

        this.websocket.send(JSON.stringify(this.form.receiveUserId)+"@"+JSON.stringify(msg));

        this.chatMsgList.push(msg)
        this.bottomScrollClick();
        this.submitForm();
      }else if(this.form.contents==null&&this.form.contents.trim().length==0){
        this.$modal.msgError("不能发送空消息");
        this.form.contents = "";
      }else {
        this.$modal.msgError("请选择聊天对象");
        this.form.contents = "";
      }
    },
    bottomScrollClick() {
      this.$nextTick(() => {
        let scrollElem  = this.$refs.mianscroll;

        console.log("scrollElem",scrollElem.scrollHeight)
        scrollElem.scrollTo({ top: scrollElem.scrollHeight, behavior: 'smooth' });
      });
    },
    /**
     配置websocket的参数和回调函数
     */
    webSocketConfig(){
      let that = this;
//判断当前浏览器是否支持WebSocket
      if('WebSocket' in window){
        //连接WebSocket节点
        this.websocket = new WebSocket('ws://localhost:8080/server/'+this.userId);
      }
      else{
        alert('Not support websocket')
      }

      //连接发生错误的回调方法
      this.websocket.onerror = function(){
        console.log("error");
      };

      //连接成功建立的回调方法
      this.websocket.onopen = function(){
        console.log("连接成功");
      }

      //接收到消息的回调方法
      this.websocket.onmessage = function(event){

        console.log(event.data);
        console.log(that.chatMsgList)
        console.log(JSON.parse(event.data))
        that.chatMsgList.push(JSON.parse(event.data));
        that.bottomScrollClick();
      }


      //连接关闭的回调方法
      this.websocket.onclose = function(){
        console.log("close");
      }

    },

  }
};
</script>
<style>
.chat-msg{
  width: 100%;
  //background: #010199;
  height: 450px;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  //visibility:hidden;
}

.write{
  display: flex;
  flex-display: row;
  justify-content:center;

  position: fixed;
  bottom: 0;

}


.bubble{

  width: 800px;


  margin: 20px 20px 0px 30px;

  height: 45px;
  display: flex;
  flex-direction: row;
  align-content: center;
  justify-content: left;
}
.bubble1{

  width: 800px;


  margin: 20px 20px 0px 30px;

  height: 45px;

  display: flex;
  flex-direction: row-reverse;
  align-content: center;
  justify-content: right;
}
.msg-content{
  background: #C9E7FF;
  border-radius: 20px 0 20px 20px;
  padding: 10px 10px 15px 10px;

}
.msg-content1{
  background: #FFFFFF;
  border-radius:0 20px  20px 20px;
  padding: 10px 10px 15px 10px;

}

</style>
